package com.fau.hm.security;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import com.fau.hm.entity.MedicalLog;
import com.fau.hm.service.IUserManagerService;

/**
 * @desc 登录日志
 * @author liy
 * @datetime 2014年8月13日,下午4:51:14
 */
@Service
public class MyLoginRecord extends SavedRequestAwareAuthenticationSuccessHandler{
	
//	@Resource
//	private ILogManagerService log;
	@Resource
	private IUserManagerService userMng;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws ServletException, IOException {
		UserDetails user = (UserDetails)authentication.getPrincipal();
		// 获得用户最后一次登录时间
//				HttpSession si = request.getSession();
//				String lastLoginTime = this.userMng.findUserLastLoginTime(user.getUsername());
//				if(StringUtils.isBlank(lastLoginTime)) {
//					si.setAttribute("lastLoginTime", "您是第一次登录");
//				} else {
//					si.setAttribute("lastLoginTime", lastLoginTime);
//				}
		
		// 创建日志对象
		MedicalLog medicalLog = new MedicalLog();
		medicalLog.setUserName(user.getUsername());
		medicalLog.setContent("登录");
//		medicalLog.setTitle("登录");
		String ipAdd = this.getIpAddr(request);
		medicalLog.setIp(ipAdd);
//		medicalLog.setType(SystemConfig.SYS_LOGIN_LOG);
//		log.saveLog(medicalLog);
		
		super.onAuthenticationSuccess(request, response, authentication);
	}
	
	/**
	 * @desc 获得用户ip
	 * @param request
	 * @return String
	 * @author liy
	 * @datetime 2014年11月13日,上午11:15:24
	 */
	private String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	} 
}
